import { useCallback, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form';
import md5 from 'blueimp-md5';
import Cookies from 'js-cookie';
import createInjection, {SetupContext} from '@/utils/inject.utils';

import styles from './index.module.css'

const Login = () => {
    const { register, handleSubmit, setError, formState: { errors } } = useForm();
    const { setIsLogin } = useLogin();

    const handlelogin = useCallback((data: Record<string, string>) => {
        const reslut = md5(`${data.password}joylive@KS`);

        if (reslut === 'c27dd14bf43cc9d54c6ec21640c9e455') {
            Cookies.set('token', md5('c27dd14bf43cc9d54c6ec21640c9e455'), {expires: 1});
            setIsLogin?.(true);
            return;
        }

        setError('password', {
            message: '密码不正确，请重新输入！',
            type: 'wrong'
        })
    }, [setError, setIsLogin])

    return (
        <div className={styles.loginWrapper}>
            <div className={styles.loginContent}>
                <div className={styles.loginTitle}>提示</div>
                <form onSubmit={handleSubmit(handlelogin)} className={styles.loginForm}>
                    <p className={styles.inputEyebrow}>请输入密码</p>
                    <input type="password" {...register('password', { required: true })} className={styles.input} data-error={!!errors.password}/>
                    {errors.password?.type === 'requied' && <span className={styles.error}>密码不能为空！</span>}
                    {errors.password?.type === 'wrong' && <span className={styles.error}>{errors.password.message as string}</span>}
                    <div className={styles.btnWrapper}>
                        <input type='submit' className={styles.submit} />
                    </div>
                </form>
            </div>
        </div>
    )
}

export default Login

interface LoginContextInte {
    isLogin: boolean,
    setIsLogin?: (arg: boolean) => void
}

const [injectLogin, useLogin] = createInjection<LoginContextInte>({
    defaultState: { isLogin: false },
    Injection: ({setupContext}: {
        setupContext: SetupContext<LoginContextInte>
    }) => {
        const [isLogin, setIsLogin] = useState(false);

        useEffect(() => {
            if (Cookies.get('token') === md5('c27dd14bf43cc9d54c6ec21640c9e455')) {
                setIsLogin(true);
                Cookies.set('token', md5('c27dd14bf43cc9d54c6ec21640c9e455'), {expires: 1});
            }
        }, [])
    
        useEffect(() => {
            setupContext({ isLogin, setIsLogin })
        }, [isLogin])
        return <></>
    }
})

export { injectLogin, useLogin}

